﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESRI.ArcGIS.Geodatabase;
using System.IO;
using hzGis.utils;
using hzGis.model;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geometry;
using System.Windows.Forms;

namespace hzGis.service.impl
{
    public class AnalysisDlService: IAnalysisDlService
    {
        private IFileService fileService;
        private MapToolService mapToolService;
        private StyleService styleService;
        public AnalysisDlService()
        {
            fileService = new FileService();
            mapToolService = new MapToolService();
            styleService = new StyleService();
        }
        public int analysisMaxYear(IFeatureClass shpFeatureClass)
        {
            IFields fileds = shpFeatureClass.Fields;
            int year = -1;
            int temp = -1;
            for (var i = 0; i < fileds.FieldCount; i++ )
            {
                IField field = fileds.get_Field(i);
                if (field.Name.IndexOf("fxdlmc") >= 0)
                {
                    string name = field.Name.Substring(0, 4);
                    temp = Convert.ToInt16(name);
                    if (temp > year)
                    {
                        year = temp;
                    }
                }
            }
            return year;
        }


        public List<Dictionary<string, object>> analysisJsydByYear(IFeatureClass shpFeatureClass, int maxYear, string dlJsonFile)
        {
            int minYear = 1999;
            string text = File.ReadAllText(dlJsonFile);
            DlModels data = JsonHelper.JsonDeserialize<DlModels>(text);
            IFields fields = shpFeatureClass.Fields;
            List<Dictionary<string, object>> result = new List<Dictionary<string, object>>();
            string tj = "(";
            for (var i = 0; i < data.dls.Count; i++)
            {
                DlModel dlModel = data.dls[i];
                if (i != data.dls.Count - 1)
                {
                    tj += "'" + dlModel.dlmc + "', ";
                }
                else
                {
                    tj += "'" + dlModel.dlmc + "' ";
                }
            }
            tj += ")";
            // 获取分别要查询年份间隔
            for (var i = 0; i < (maxYear - minYear); i++)
            {
                int beforeYear = maxYear - (i + 1);
                int afterYear = maxYear - i;
                // 查询afterYear为建设用地但beforeYear为非建设用地的数据
                string afterField = "";
                string afterFieldFat = "";
                string beforeField = "";
                string beforeFieldFat = "";
                afterField = "" + afterYear + "fxdlmc";
                beforeField = "" + beforeYear + "fxdlmc";
                if (isExist(fields, afterField))
                {
                    if (isExist(fields, beforeField))
                    {
                        afterFieldFat = "\"" + afterYear + "fxdlmc\"";
                       // afterField = afterYear + "FXDLMC";
                        beforeFieldFat = "\"" + beforeYear + "fxdlmc\"";
                       // beforeField = beforeYear + "FXDLMC";
                    }
                    else
                    {
                        afterFieldFat = "\"" + afterYear + "fxdlmc\"";
                       // afterField = afterYear + "FXDLMC";
                        beforeFieldFat = "\"" + beforeYear + "dlmc\"";
                       // beforeField = beforeYear + "DLMC";
                        beforeField = "" + beforeYear + "dlmc";
                    }
                }
                else
                {
                    afterFieldFat = "\"" + afterYear + "dlmc\"";
                    afterField = afterYear + "dlmc";
                    beforeFieldFat = "\"" + beforeYear + "dlmc\"";
                    beforeField = beforeYear + "dlmc";
                }

                string where = afterFieldFat + " in " + tj + " and " + beforeFieldFat + " not in" + tj;
                if (afterYear == 2018 && beforeYear == 2017)
                {
                    Console.WriteLine(where);
                }
                Dictionary<string, object> item = queryYearData(shpFeatureClass, where, beforeYear, afterYear, afterField, beforeField);
                result.Add(item);
            }
            // 查询1999年的数据
            string afterFieldFat1999 = "\"" + 1999 + "dlmc\"";
            string afterField1999 = 1999 + "DLMC";
            string where1999 = afterFieldFat1999 + " in " + tj;
            Dictionary<string, object> item1999 = queryYearData(shpFeatureClass, where1999, 1999, 1999, afterField1999, afterField1999);
            result.Add(item1999);
            return result;
        }


        private Dictionary<string, object> queryYearData(IFeatureClass shpFeatureClass, string where, int beforeYear, int afterYear, string afterField, string beforeField)
        {
            List<string> vals = new List<string>();
            IQueryFilter qf = new QueryFilter();
            qf.WhereClause = where;
            IFeatureCursor fc = shpFeatureClass.Search(qf, false);
            IFeature pFeature = null;
            double jsydArea = 0;
            while ((pFeature = fc.NextFeature()) != null)
            {
                int num = pFeature.Fields.FindField("gid");
                string val = pFeature.get_Value(num);
                IArea area = pFeature.Shape as IArea;
                jsydArea += area.Area;
                vals.Add(val);
            }
            if (afterYear == 2018)
            {
                Console.WriteLine(jsydArea);
            }
            Dictionary<string, object> item = new Dictionary<string, object>();
            item.Add("beforeYear", beforeYear);
            item.Add("afterYear", afterYear);
            item.Add("vals", vals);
            item.Add("jsydArea", jsydArea);
            item.Add("afterField", afterField);
            item.Add("beforeField", beforeField);
            return item;
        }

        private Boolean isExist(IFields fields, string fieldName)
        {
            bool res = false;
            for (int i = 0; i < fields.FieldCount; i++)
            {
                IField field = fields.get_Field(i);
                
                if (field.Name.ToLower() == fieldName.ToLower())
                {
                    res = true;
                    break;
                }
            }
            return res;
        }

        public bool changeLayer(AxMapControl axMap, AxPageLayoutControl axPage, Dictionary<string, object> result, ILayer resultLayer, string dl)
        {
            bool res = false;
            int afterYear = (int)result["afterYear"];
            int beforeYear = (int)result["beforeYear"];
            // 修改对应的地类数据
            for (var i = 0; i < axMap.LayerCount; i++)
            {
                ILayer layer = axMap.get_Layer(i);
                if (layer.Name.IndexOf("44") >= 0)
                {
                    string shpPath = dl + "\\" + afterYear + "\\" + layer.Name + "\\DLTB.shp";
                    if (File.Exists(shpPath))
                    {
                        IFeatureClass featureClass = fileService.openFeatureClassByShp(shpPath);
                        hzGis.utils.MemoryHelper.ReleaseFeatureClass(((IFeatureLayer)layer).FeatureClass);
                        ((IFeatureLayer)layer).FeatureClass = featureClass;
                        res = true;
                    }
                    else
                    {
                        res = false;
                    }
                }
            }
            if (res)
            {
                if (afterYear == 2018)
                {
                    Console.WriteLine(afterYear);
                }
                styleService.setStylePro(resultLayer, new byte[] { 55, 148, 31 }, 4, new byte[] { 55, 148, 31, 1 }, result["afterField"].ToString(), (List<string>)result["vals"]);
                axMap.ActiveView.Refresh();
                mapToolService.CopyToPageLayout(axMap, axPage);
            }
            return res;
        }


        public List<string> anslysisXzq(IFeatureClass xqFeatureClass, IFeatureClass bphxFeatureClass)
        {
            List<string> xzqs = new List<string>();
            ISpatialFilter spatialFilter = new SpatialFilter();
            IGeoDataset featureDataset = bphxFeatureClass as IGeoDataset;
            IEnvelope featureExtent = featureDataset.Extent;
            spatialFilter.Geometry = featureExtent;
            spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
            IFeatureCursor fc =  xqFeatureClass.Search(spatialFilter, false);
            IFeature feature = null;
            while ((feature = fc.NextFeature()) != null)
            {
                int fqIndex = feature.Fields.FindField("FQ");
                string fq = feature.get_Value(fqIndex);
                if (xzqs.Count == 0)
                {
                    xzqs.Add(fq);
                }
                else
                {
                    for (var i = 0; i < xzqs.Count; i++)
                    {
                        string xzq = xzqs[i];
                        if (xzq != fq)
                        {
                            xzqs.Add(fq);
                        }
                    }
                }
            }
            return xzqs;
        }


        public string getDirName(string fq)
        {
            string dirName = null;
            switch(fq){
                case "惠阳":
                    dirName = "441303";
                    break;
                case "博罗":
                    dirName = "441322";
                    break;
                case "大亚湾":
                    dirName = "4413031";
                    break;
                case "惠城":
                    dirName = "441302";
                    break;
                case "惠东":
                    dirName = "441323";
                    break;
                case "龙门":
                    dirName = "441324";
                    break;
                case "仲恺":
                    dirName = "4413021";
                    break;
                default:
                    dirName = null;
                    break;
            }
            return dirName;
        }


        public void changeLayerByYear(AxMapControl axMap, AxPageLayoutControl axPage, int year)
        {
            for (var i = 0; i < axMap.LayerCount; i++)
            {
                ILayer layer = axMap.get_Layer(i);
                if (layer.Name.IndexOf("44") >= 0)
                {
                    IFeatureClass featureClass = ((IFeatureLayer)layer).FeatureClass;
                    string shpPath = fileService.GetPath(featureClass);
                    if (shpPath.IndexOf(year.ToString()) < 0)
                    {
                        shpPath = "D:\\code\\Hz\\ydbp\\data\\DLTB\\" + year + "\\" + layer.Name + "\\DLTB.shp";
                        if (File.Exists(shpPath))
                        {
                            IFeatureClass targetfeatureClass = fileService.openFeatureClassByShp(shpPath);
                            hzGis.utils.MemoryHelper.ReleaseFeatureClass(((IFeatureLayer)layer).FeatureClass);
                            ((IFeatureLayer)layer).FeatureClass = targetfeatureClass;
                        }
                    }
                    axMap.ActiveView.Refresh();
                    mapToolService.CopyToPageLayout(axMap, axPage);
                }
            }
        }



        public IPoint sumCenterByRectange(IFeatureClass featureClass, double xmin, double xmax, double ymin, double ymax, int type, int i, int pages)
        {
            IEnvelope fwEnvelope = new Envelope() as IEnvelope;
            fwEnvelope.XMax = xmax;
            fwEnvelope.XMin = xmin;
            fwEnvelope.YMax = ymax;
            fwEnvelope.YMin = ymin;
            ISpatialFilter spatialFilter = new SpatialFilter();
            spatialFilter.Geometry = fwEnvelope;
            spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
            IFeatureCursor fc = featureClass.Search(spatialFilter, false);
            IFeature feature = fc.NextFeature();
            if (feature == null)
            {
                return null;
            }
            else
            {
                // 进行图形裁剪
                List<IEnvelope> es = new List<IEnvelope>();
                while (feature != null)
                {
                    ITopologicalOperator pTopologBoundary = feature.Shape as ITopologicalOperator;
                    pTopologBoundary.Clip(fwEnvelope);
                    if (feature.Shape != null)
                    {
                        IPolygon p = feature.Shape as IPolygon;
                        IArea pa = p as IArea;
                        Console.WriteLine(pa.Area);
                        if (pa.Area != 0)
                        {
                            IEnvelope envelope = new Envelope() as IEnvelope;
                            p.QueryEnvelope(envelope);
                            es.Add(envelope);
                        }
                    }
                    feature = fc.NextFeature();
                }
                double[] xy = sumMaxRectange(es);
                if (xy[1] == 0 && xy[0] == 0 && xy[3] == 0 && xy[2] == 0)
                {
                    return null;
                }
                else
                {
                    IPoint point = new Point();
                    if (type == 0)
                    {
                        // 如果打印范围>图形范围
                    }
                    else if (type == 1)
                    {
                        //打印范围高度小于地图范围高度大于地图范围
                        if (i < pages - 1)
                        {
                            point.X = (xy[1] + xy[0]) / 2;
                            point.Y = (xy[3] + xy[2]) / 2;
                        }
                        else
                        {
                            point.X = (xy[1] + xy[0]) / 2;
                            point.Y = (ymax + ymin) / 2;
                        }

                    }
                    else if (type == 2)
                    {
                        //打印范围宽度大于地图范围宽度范围小于地图范围
                        if (i < pages - 1)
                        {
                            point.X = (xy[1] + xy[0]) / 2;
                            point.Y = (xy[3] + xy[2]) / 2;
                        }
                        else
                        {
                            point.X = (xmax + xmin) / 2;
                            point.Y = (xy[3] + xy[2]) / 2;
                        }
                    }
                    else if (type == 3)
                    {
                        //打印范围<地图范围
                        if (i < pages)
                        {
                            point.X = (xy[1] + xy[0]) / 2;
                            point.Y = (xy[3] + xy[2]) / 2;
                        }
                        else
                        {
                            point.X = (xmax + xmin) / 2;
                            point.Y = (ymax + ymin) / 2;
                        }
                    }
                    return point;
                }
            }
        }
        private double[] sumMaxRectange(List<IEnvelope> es)
        {
            double xmin = 0, xmax = 0, ymin = 0, ymax = 0;
            for (var i = 0; i < es.Count; i++)
            {
                IEnvelope e = es[i];
                if (i == 0)
                {
                    xmin = e.XMin; xmax = e.XMax; ymin = e.YMin; ymax = e.YMax;
                }
                else
                {
                    if (e.XMin < xmin){ xmin = e.XMin;}
                    if (e.YMin < ymin) { ymin = e.YMin; }
                    if (e.XMax > xmax) { xmax = e.XMax; }
                    if (e.YMax > ymax) { ymax = e.YMax; }
                }
            }
            return new double[] { xmin, xmax, ymin, ymax};
        }
    }
}
